package com.yanqu.road.logic.config;

import com.yanqu.road.utils.TimeHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Date;
import java.util.HashMap;

public class TempConfig {
    private static final Logger logger = LogManager.getLogger(TempConfig.class.getName());

    public static Object parseValue(Class<?> fieldType, String value) {

        try {
            Object parseValue = null;
            String v = value.trim();
            if (fieldType == Integer.class) {
                parseValue = Integer.parseInt(v);
            } else if (fieldType == Long.class) {
                parseValue = Long.parseLong(v);
            } else if (fieldType == Boolean.class) {
                parseValue = Boolean.parseBoolean(v);
            } else if (fieldType == Date.class) {
                if (v.length() > 10) {
                    if (v.indexOf('-') != -1)
                        parseValue = TimeHelper.getSimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(v);
                    else
                        parseValue = TimeHelper.getSimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(v);
                } else if (v.length() == 8)
                    parseValue = TimeHelper.getSimpleDateFormat("HH:mm:ss").parse(v);
                else if (v.indexOf('-') != -1)
                    parseValue = TimeHelper.getSimpleDateFormat("yyyy-MM-dd").parse(v);
                else
                    parseValue = TimeHelper.getSimpleDateFormat("yyyy/MM/dd").parse(v);
            } else if (fieldType == Double.class) {
                parseValue = Double.parseDouble(v);
            } else if (fieldType == Float.class) {
                parseValue = Float.parseFloat(v);
            } else {
                parseValue = v;
            }
            return parseValue;
        } catch (Exception e) {
            logger.error("解析配置数值异常: ", e);
            return null;
        }
    }

    static void Load(Class<?> type, HashMap<String, String> allConfigs) {
        for (java.lang.reflect.Field field : type.getFields()) {
            ConfigPropertyAnnotation annotation = field.getAnnotation(ConfigPropertyAnnotation.class);
            if (annotation != null) {
                String configInfo = allConfigs.get(annotation.key());
                String valueString = annotation.defaultValue();

                if (configInfo != null && configInfo.length() > 0) {
                    valueString = configInfo;
                }

                try {
                    field.set(null, parseValue(annotation.type(), valueString));
                } catch (Exception e) {
                    logger.error("{} fail to load:{},error:{}", type.getName(), valueString, e);
                }
            }
        }
    }


}
